<template>
  <el-dialog
    v-loading="loading"
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="open"
    width="850px"
    append-to-body
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="auto"
      :disabled="disabled"
      :class="{ 'detail-disabled': disabled }"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="form.projectName" placeholder="请输入项目名称" />
      </el-form-item>
      <el-form-item label="项目编号" prop="projectNumber">
        <el-input v-model="form.projectNumber" placeholder="请输入项目编号" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="form.projectType" placeholder="请选择项目类型" clearable>
          <el-option v-for="dict in dict.type.project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目级别" prop="projectLevel">
        <el-select v-model="form.projectLevel" placeholder="请选择项目级别" clearable>
          <el-option
            v-for="dict in dict.type.project_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目进度" prop="projectProgress">
        <el-select v-model="form.projectProgress" placeholder="请选择项目进度" clearable>
          <el-option
            v-for="dict in dict.type.project_progress"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input v-model="form.companyName" placeholder="请输入公司名称" />
      </el-form-item>
      <el-form-item v-if="false" label="封面" prop="coverImg">
        <image-upload
          :limit="1"
          @input="
            (val) => {
              form.coverImg = val
            }
          "
          :value="form.coverImg"
        />
      </el-form-item>

      <el-form-item label="项目金额" prop="contractAmount">
        <el-input-number
          controls-position="right"
          :step="100"
          style="width: 150px"
          :precision="2"
          :min="0"
          v-model.number="form.contractAmount"
          placeholder="项目金额"
        >
        </el-input-number>
        元
      </el-form-item>
      <el-form-item label="签约主体" prop="signingBody">
        <el-input v-model="form.signingBody" placeholder="请输入签约主体" />
      </el-form-item>
      <el-form-item label="下周工作安排" prop="nextWeekWorkSchedule">
        <editor v-if="open" :readOnly="disabled" v-model="form.nextWeekWorkSchedule" :min-height="192" />
      </el-form-item>

      <!-- <el-form-item label="开标时间" prop="biddingDate">
        <el-date-picker
          clearable
          v-model="form.biddingDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开标时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="中标时间" prop="winBiddingDate">
        <el-date-picker
          clearable
          v-model="form.winBiddingDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择中标时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="合同签约时间" prop="contractSigningDate">
        <el-date-picker
          clearable
          v-model="form.contractSigningDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择开标时间"
        >
        </el-date-picker>
      </el-form-item>

      <!-- <el-form-item label="业务线" prop="businessLine">
        <el-input v-model="form.businessLine" placeholder="请输入业务线" />
      </el-form-item> -->
      <el-form-item label="商务负责人" prop="businessManager">
        <el-input v-model="form.businessManager" placeholder="请输入商务负责人" />
      </el-form-item>
      <el-form-item label="项目负责人" prop="projectManager">
        <el-input v-model="form.projectManager" placeholder="请输入项目负责人" />
      </el-form-item>
      <!-- <el-form-item label="客户" prop="customerIds">
          <el-select
            v-model="form.customerIds"
            placeholder="请输入关键词"
            :remote-method="getCustomer"
            multiple
            filterable
            remote
            reserve-keyword
            clearable
            :loading="customerLading"
          >
            <el-option v-for="dict in customerData" :key="dict.id" :label="dict.customerName" :value="dict.id" />
          </el-select>
        </el-form-item> -->

      <el-form-item label="附件" prop="annexList">
        <image-upload
          @input="
            (val) => {
              const imageList = val.split(',')
              form.annexDtoList = imageList.map((item) => {
                return {
                  name: new Date().getTime(),
                  url: item,
                }
              })
            }
          "
          :limit="20"
          :value="form.annexList"
        />
      </el-form-item>
      <el-form-item v-if="form.id">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="客户信息" name="customerDetails">
            <el-table
              :data="activeData"
              style="width: 100%"
              @row-click="rowClick"
              v-loading="activeLoading"
              row-class-name="tableColumn"
              :header-cell-style="{ background: '#fff' }"
            >
              <el-table-column prop="customerName" align="center" label="客户名称"> </el-table-column>
              <el-table-column align="center" label="客户标签">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.customer_tag" :value="scope.row.tagId" />
                </template>
              </el-table-column>
              <el-table-column prop="companyName" align="center" label="单位名称"> </el-table-column> </el-table
          ></el-tab-pane>
          <el-tab-pane label="拓展信息" name="expansionDetails"
            ><el-table
              :data="activeData"
              style="width: 100%"
              @row-click="rowClick"
              v-loading="activeLoading"
              row-class-name="tableColumn"
              :header-cell-style="{ background: '#fff' }"
            >
              <el-table-column prop="expansionName" align="center" label="拓展名称"> </el-table-column>
              <el-table-column prop="expansionType" align="center" label="拓展类型">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.expansion_type_level" :value="scope.row.expansionType" />
                </template>
              </el-table-column>
              <el-table-column prop="expenses" align="center" label="支出"> </el-table-column>
              <el-table-column prop="createTime" align="center" label="拓展时间"> </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="合同信息" name="contractDetails"
            ><el-table
              :data="activeData"
              style="width: 100%"
              @row-click="rowClick"
              v-loading="activeLoading"
              row-class-name="tableColumn"
              :header-cell-style="{ background: '#fff' }"
            >
              <el-table-column prop="contractName" align="center" label="合同名称"> </el-table-column>
              <el-table-column prop="contractNumber" align="center" label="合同编号"> </el-table-column>
              <el-table-column prop="categoryName" align="center" label="合同分类"> </el-table-column>
              <el-table-column prop="contractAmount" align="center" label="合同金额"> </el-table-column> </el-table
          ></el-tab-pane>
          <el-tab-pane label="供应商" name="supplierDetails"
            ><el-table
              :data="activeData"
              style="width: 100%"
              @row-click="rowClick"
              v-loading="activeLoading"
              row-class-name="tableColumn"
              :header-cell-style="{ background: '#fff' }"
            >
              <el-table-column prop="supplierName" align="center" label="供应商名称"> </el-table-column>
              <el-table-column prop="supplierTypeName" align="center" label="供应商类型"> </el-table-column>
              <el-table-column prop="contactNumber" align="center" label="标签">
                <template slot-scope="scope">
                  <span v-for="(tag, index) in scope.row.supplierTagList">{{
                    `${index !== 0 ? '、' : ''}${tag.tagTypeName}`
                  }}</span>
                </template>
              </el-table-column>
            </el-table></el-tab-pane
          >
        </el-tabs>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="!disabled">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
    <customer-details
      :show="modelName === 'customerDetails'"
      :disabled="true"
      :id="modelData.id"
      @cancel="handleOpenModel"
    />
    <contract-details
      :show="modelName === 'contractDetails'"
      :disabled="true"
      @cancel="handleOpenModel"
      :id="modelData.contractId"
    />
    <supplier-details
      :show="modelName === 'supplierDetails'"
      :disabled="true"
      @cancel="handleOpenModel"
      :id="modelData.id"
    />
  </el-dialog>
</template>
<script>
import { getProject, updateProject, addProject } from '@/api/biz/project'
import { listCustomer } from '@/api/biz/customer'
import { listInformation } from '@/api/biz/contract'
import { listSupplier } from '@/api/biz/supplier'
import ImageUpload from '@/components/ImageUpload'
export default {
  name: 'ProjectDetailsChildren',
  components: {
    ImageUpload,
    CustomerDetails: () => import('@/components/biz/CustomerDetails.vue'),
    ContractDetails: () => import('@/components/biz/ContractDetails.vue'),
    SupplierDetails: () => import('@/components/biz//SupplierDetails.vue'),
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String || Number,
      default: '',
    },
  },
  data() {
    var checkAmount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error())
      }
      setTimeout(() => {
        if (typeof value !== 'number' || Number.isNaN(value)) {
          callback(new Error())
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      open: false,
      title: '',
      // 遮罩层
      loading: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        signingBody: [{ required: true, message: '请输入签约主体', trigger: 'blur' }],
        projectNumber: [{ required: true, message: '请输入项目编号', trigger: 'blur' }],
        projectType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
        projectLevel: [{ required: true, message: '请选择项目级别', trigger: 'change' }],
        contractAmount: [{ required: true, validator: checkAmount, message: '请输入项目金额', trigger: 'blur' }],
        projectProgress: [{ required: true, message: '请选择项目进度', trigger: 'change' }],
      },
      customerLading: false,
      customerData: [],
      modelName: '',
      modelData: {},
      activeData: [],
      activeName: 'customerDetails',
      activeLoading: false,
    }
  },
  dicts: ['project_type', 'project_level', 'project_progress', 'expansion_type_level', 'customer_tag'],
  watch: {
    show: {
      handler(val) {
        this.open = val
      },
    },
    open: {
      handler(val) {
        this.reset()
        if (val) {
          if (this.disabled) {
            this.title = '查看项目信息'
          } else {
            this.title = this.id ? '修改项目信息' : '添加项目信息'
          }
          if (this.id) {
            this.loading = true
            getProject(this.id)
              .then((response) => {
                response.data.id = this.id
                this.loading = false
                response.data.annexList = response.data.annexDtoList.map((item) => item.url)
                this.form = response.data
                this.getTabTableData()
              })
              .catch(() => {
                this.loading = false
              })
          }
        } else {
          this.activeData = []
          this.activeName = 'customerDetails'
          this.$emit('cancel', false)
        }
      },
    },
  },

  methods: {
    getTabTableData() {
      const data = {
        projectId: this.form.id,
        pageNum: 1,
        pageSize: 50,
      }
      const successFn = (response) => {
        this.activeLoading = false
        this.activeData = response.rows
      }
      const failFn = () => {
        this.activeLoading = false
      }
      this.activeLoading = true
      if (this.activeName === 'customerDetails') {
        listCustomer(data).then(successFn).catch(failFn)
        return
      }
      if (this.activeName === 'contractDetails') {
        listInformation(data).then(successFn).catch(failFn)
        return
      }
      if (this.activeName === 'supplierDetails') {
        listSupplier(data).then(successFn).catch(failFn)
      }
    },
    rowClick(row) {
      this.handleOpenModel(this.activeName, row)
    },
    handleClick(tab, event) {
      this.activeData = []
      this.$nextTick(() => {
        this.getTabTableData()
      })
    },
    // 取消按钮
    cancel() {
      this.reset()
      this.open = false
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        projectNumber: null,
        projectType: null,
        companyName: null,
        projectLevel: null,
        contractAmount: null,
        projectManager: null,
        projectProgress: null,
        biddingDate: null,
        businessManager: null,
        annexDtoList: null,
        signingBody: null,
        businessLine: null,
        businessManager: null,
        contractSigningDate: null,
        winBiddingDate: null,
        contractSigningDate: null,
        coverImg: null,
        // customerIds: null,
      }
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.form.id != null) {
            updateProject(this.form)
              .then((response) => {
                this.$modal.msgSuccess('修改成功')
                this.loading = false
                this.open = false
                this.$emit('refresh')
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            addProject(this.form)
              .then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.loading = false
                this.open = false
                this.$emit('refresh')
              })
              .catch(() => {
                this.loading = false
              })
          }
        }
      })
    },
    handleOpenModel(name = '', data = {}) {
      this.modelName = name
      this.modelData = data
    },

    getCustomer(query = '') {
      this.customerLading = true
      listCustomer({ customerName: query, pageNum: 1, pageSize: 10 })
        .then((res) => {
          this.customerData = res.rows
          this.customerLading = false
        })
        .catch((error) => {
          this.customerLading = false
        })
    },
  },
}
</script>
<style scoped lang="scss">
.scrollMenuBox {
  width: 100%;
  height: 450px;
}
.title {
  padding: 15px 0;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
<style>
.tableColumn {
  cursor: pointer;
}
</style>
